package com.xs.server;

import java.util.Random;

import org.apache.log4j.Logger;

import com.xs.CommandType;
import com.xs.CustomProtcol;
import com.xs.client.entity.RpcRequest;
import com.xs.client.entity.RpcResponse;
import com.xs.constant.NettyConstants;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class ServerHandler extends ChannelInboundHandlerAdapter {

	private static final Logger logger = Logger.getLogger(ServerHandler.class);

	private int loss_connect_count = 0;

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("客户端：" + ctx.channel().remoteAddress() + "已连接,.," + Thread.currentThread().getName() + "channel："
				+ ctx.channel());
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		ctx.fireChannelInactive();
		logger.info("客户端：" + ctx.channel().remoteAddress() + "已断开,.," + Thread.currentThread().getName() + "channel："
				+ ctx.channel());

	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			IdleState state = event.state();
			if (state == IdleState.READER_IDLE) {
				loss_connect_count++;
				logger.info(String.valueOf(NettyConstants.SERVER_READ_IDEL_TIME_OUT * loss_connect_count)
						+ "秒没有接收到客户端的信息了");
				if (NettyConstants.SERVER_READ_IDEL_TIME_OUT
						* loss_connect_count >= NettyConstants.MAX_LOSS_CONNECT_TIME) {
					logger.info("------------服务器主动关闭客户端链路");
					ctx.channel().close();
				}
			}
		} else {
			super.userEventTriggered(ctx, evt);
		}
	}

	@Override
	public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {

		Thread.sleep(new Random().nextInt(10) * 1000);

		if (msg instanceof CustomProtcol) {
			@SuppressWarnings("unchecked")
			CustomProtcol<RpcRequest> req = (CustomProtcol<RpcRequest>) msg;

			logger.debug("服务器端线程为:" + Thread.currentThread().getName() + "；服务器收到消息内容为：" + req.toString());

			CustomProtcol<RpcResponse> resMsg = new CustomProtcol<RpcResponse>();
			RpcResponse response = new RpcResponse();
			response.setResponseId(req.getBody().getRequestId());

			if (req.getCommand() == CommandType.QUESTION) {
				String responseStr = calc(req.getBody().getBody());
				response.setResponseStr(responseStr);
				resMsg.setBody(response);
			} else {
				resMsg.setBody(response);
			}

			resMsg.setCommand(CommandType.READ);

			boolean close = false;
			if (req.getCommand() == CommandType.CLOSE) {
				close = true;
				resMsg.setCommand(CommandType.CLOSE);
			}

			ChannelFuture future = ctx.writeAndFlush(resMsg);

			future.addListener(f -> {
				if (f.isSuccess()) {
					logger.debug(
							"服务器端线程为:" + Thread.currentThread().getName() + "；服务器回复客户端消息内容：" + response.toString());
				}
			});

			if (close) {
				future.addListener(ChannelFutureListener.CLOSE);
			}

		}

	}

	public String calc(String question) {
		String resultStr = "";
		if (question != null && question.length() > 0) {
			try {
				String content = question;
				String array[] = content.split("=");
				int result = Integer.parseInt(array[0].split("加")[0]) + Integer.parseInt(array[0].split("加")[1]);
				resultStr = content.replaceAll("[?]", "") + result;
			} catch (NumberFormatException e) {
				resultStr = "参数不对。。。" + e.getMessage();
				e.printStackTrace();
				return resultStr;
			}
		} else {
			resultStr = "请输入问题？";
		}

		return resultStr;
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		if (ctx != null) {
			ctx.close();
		}
		logger.error(cause);

	}

}
